package com.yixiu.study.juc.copyonwrite;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @CalssName T01_CopyOnWrite
 * @Description
 * @Author yixiu
 * @Date 2021/6/29 9:25
 * @Verison 1.0
 **/
public class T01_CopyOnWrite {

    public static void main(String[] args) {
//        List<String> lists = new ArrayList<>();//线程不安全
//        List<String> lists = new Vector<>();//线程安全
        List<String> lists = new CopyOnWriteArrayList<>();//线程安全，因为是写时复制，所以效率低
        Random r = new Random();
        Thread[] ths = new Thread[100];

        for (int i = 0; i < ths.length; i++) {
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 1000; i++) {
                        lists.add("a" + r.nextInt(10000));
                    }
                }
            };
            ths[i] = new Thread(task);
        }

        runAndComputeTime(ths);
        System.out.println(lists.size());
    }

    static void runAndComputeTime(Thread[] ths){
        long s1 = System.currentTimeMillis();
        Arrays.asList(ths).forEach(t -> t.start());
        Arrays.asList(ths).forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        long s2 = System.currentTimeMillis();
        System.out.println(s2 - s1);
    }

}
